package com.clive.controller;

import com.clive.bean.DishesCategory;
import com.clive.service.DishesCategoryService;
import com.clive.service.impl.DishesCategoryServiceimpl;
import com.clive.vo.DishResult;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "DishesCategoryController",urlPatterns = {"/servlet-demo/dishCategory"})
public class DishesCategoryController extends HttpServlet {
    private DishesCategoryService categoryService;
    private ObjectMapper mapper;
    @Override
    public void init() throws ServletException {
        categoryService = new DishesCategoryServiceimpl();
        mapper = new ObjectMapper();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("op");
        if ("findAll".equals(op)) {
            List<DishesCategory> list = categoryService.findDishesCategoryAll();
            DishResult result = DishResult.ok(list);
            String json = mapper.writeValueAsString(result);
            response.getWriter().print(json);
        }else if ("addDishCategory".equals(op)) {
            String dishesCategoryName = request.getParameter("categoryName");
            DishesCategory dishesCategory = new DishesCategory();
            dishesCategory.setDishesCategoryName(dishesCategoryName);
            boolean b = categoryService.addDishesCategory(dishesCategory);
            DishResult result = null;
            String json = null;
            if (b) {
                result = DishResult.ok(null);
                json = mapper.writeValueAsString(result);
            }else {
                result = DishResult.error(null);
                json = mapper.writeValueAsString(result);
            }
            response.getWriter().print(json);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
